//
//  ITITUserModel.swift
//  InternalTool-Swift
//
//  Created by Daniel Hu on 11/29/16.
//  Copyright © 2016 com.mask. All rights reserved.
//

import Foundation

enum Role: Int {
    case nobody = 0         //不确定
    case worker             //施工员
    case monitor            //质量监督管理员
    case inspector          //质检员
}

class User: NSObject, NSCoding {
    
    struct Keys {
        static let name = "name"
        static let role = "role"
        static let id = "id"
        static let token = "token"
        static let auth_key = "auth_key"
        static let is_push = "is_push"
    }
    
    // MARK: Properties
    var name: String?
    var role: Role?
    var id: String?
    var token: String?
    var auth_key: String?
    var is_push: Int?
    
    static let shared: User = {
        var instance: User? = User.unarchive()
        if instance == nil {
            instance = User()
        }
        return instance!
    }()
    
    
    override init() {
        // do nothing
    }
    
    static func userPath() -> String {
        return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0].appending("/user")
    }
    
    static func unarchive() -> User? {
        let path = self.userPath()
        if FileManager().fileExists(atPath: path) {
            return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? User
        } else {
            return nil
        }
    }
    
    func archive() -> Void {
        NSKeyedArchiver.archiveRootObject(self, toFile: User.userPath())
    }
    
    func clear() {
        name = nil
        role = nil
        id = nil
        token = nil
        is_push = nil
        auth_key = nil
    }
    
    func updateUserInfo(withDictionary dic: Dictionary<String, Any>) {
        role = dic[Keys.role] as? Role
        id = dic[Keys.id] as? String
        token = dic[Keys.token] as? String
        is_push = dic[Keys.is_push] as? Int
    }
    
    // MARK: - NSCoding
    
    required init?(coder aDecoder: NSCoder) {
        super.init()
        name = aDecoder.decodeObject(forKey: Keys.name) as? String
        role = Role(rawValue: aDecoder.decodeObject(forKey: Keys.role) as! Int)
        id = aDecoder.decodeObject(forKey: Keys.id) as? String
        token = aDecoder.decodeObject(forKey: Keys.token) as? String
        auth_key = aDecoder.decodeObject(forKey: Keys.auth_key) as? String
        is_push = aDecoder.decodeObject(forKey: Keys.is_push) as? Int
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey: Keys.name)
        aCoder.encode(role?.rawValue, forKey: Keys.role)
        aCoder.encode(id, forKey: Keys.id)
        aCoder.encode(token, forKey: Keys.token)
        aCoder.encode(auth_key, forKey: Keys.auth_key)
        aCoder.encode(is_push, forKey: Keys.is_push)
    }
    
}
